<?php

namespace app\index\controller\tan;

use think\Controller;
use think\Request;
use think\Session;
use think\Db;
use app\index\controller\Log\InsertLog as IL;

/**
 * 文章
 */
class Article extends Controller
{
    use UploadFileTrait;
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        
        Ret::IfEmptyExit( Db::table("article")->alias("a")->join("users u","u.id=a.user_id")->where([
            "a.effect"=>1, 'a.user_id' => Session::get('user.id')
        ])->field("a.id,a.user_id, u.name as author_name,a.title,a.brief,a.img,a.datetime,a.volume,a.expenses")->order("a.id desc") ->paginate()->toArray(),10103);
    }

    /**
     * 获取文章详情.
     * @param id => 文章id
     * @return 文章详情
     */
    public function get($id){
        if(empty($id))
            return ReturnData::err(10011,[],'文章id不能为空');

        $article = Db::table("article")->where(['id' => $id])->find();

        if(empty($article)){
            return ReturnData::err(10012,[],'未找到该文章');
        }  
        elseif($article['effect'] == 0 ){
            return ReturnData::err(10013,[],'该文章已删除/禁用');
        }else
            return ReturnData::OK($article);
            
    }

    public function index2(DownloadFile $df){
        $df->download([
            [
                "x"=>"Asdf",
                "t"=>"asf",
                "j"=>"阿三的发表"
            ],
            [
                "t"=>"fff",
                "x"=>"aaaa",
                "j"=>"阿三的发表",
                "xf"=>date("Y-m-d H:i:s")
            ],
        ], [
            "t"=>"谭",
            "j"=>"金",
            "x"=>"星",
            "xf"=>"date",
        ]);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $post=$request->post();
        $validate=[
            "title|标题"=>"require|max:50|chsDash",
            "brief|文章简介"=>"require|max:100",
            "body|文章内容"=>"require",
            "expenses|文章资费"=>"require|float",
        ];
        Ret::IfNoTrue($this->validate($post, $validate), 10121);
        $data=Eliminate::E($post, $validate);
        $data['img']=$request->post("img");
        $data['user_id']=Session::get("user.id");
        Ret::Exit_(\think\Db::table("article")->insert($data), 10122);
    }

    /**
     * 查看文章
     * @param type $id  文章id
     * @param type $purchase  是否购买
     */
    public function read($id,$purchase=false)
    {
        $data=Db::table("article")->alias("a")->join("users u","u.id=a.user_id")->where([
                "a.effect"=>1,
                "a.id"=>$id
            ])->field("a.*,u.name as author_name")->find();
        Ret::IfEmpty( $data,10104,"无此文章或已下线");
        //文章为0元，或是作者本人。这显示
            Db::table("article")->where(['id'=>$id])->update([
                "volume"=>$data['volume']+1
            ]);
        if($data['expenses'] == 0.0 || Session("user.id") == $data['user_id'] ){
            Ret::IfEmptyExit($data, 1);
        }
       $article_reading= Db::table("article_reading")->where([
            "article_id"=>$data['id'],
            "user_id"=>Session::get("user.id")
        ])->find();
       /**
        * 代表以前购买过该文章
        */
        if(! empty($article_reading)){
            Ret::IfEmptyExit($data, 1);
        }
        if(! $purchase){
            Ret::err(10105, "该文章为付费文章，请先购买");
        }
        Db::transaction(function() use ($id,$data){
//            card_balance
            $userdata =Db::table("users")->where(['id'=>Session("user.id")]) ->field("card_balance")->find();
            if($userdata['card_balance'] < $data['expenses']){
                Db::rollback();
                Ret::err(10106, "账号余额不够，请先充值！");
            }
            Db::table("users")->where(['id'=>Session("user.id")]) ->update(["card_balance"=> $userdata['card_balance'] - $data['expenses']   ]);#购买者
            $dx=Db::table("users")->where(["id"=>$data['user_id']])->lock(true)->find();
            
            $idx=Db::table("article_reading")->insertGetId([
                "article_id"=>$id,
                "user_id"=>Session::get("user.id"),
                "datetime"=>date("Y-m-d H:i:s"),
            ]);
            if(! $idx){
                Db::rollback();
            }
            Db::table("users")->where(["id"=>$data['user_id']])->update(["card_balance"=> $dx['card_balance']+$data['expenses'] ]);#文章所有人
            IL::insert("article", [
                "user_id"=>Session("user.id"),
                "before_balance"=>$userdata['card_balance'],
                "money"=>$data['expenses'],
                "after_balance"=>$userdata['card_balance']-$data['expenses'],
                "operating"=>1,
                "type"=>0,
                "createtime"=>date("Y-m-d H:i:s"),
                "article_reading_id"=>$idx
            ]);  #购买
            IL::insert("article", [
                "user_id"=>$dx['id'],
                "before_balance"=>$dx['card_balance'],
                "money"=>$data['expenses'],
                "after_balance"=>$dx['card_balance']+$data['expenses'],
                "type"=>1,
                "createtime"=>date("Y-m-d H:i:s"),
                "article_reading_id"=>$idx
            ]);#收入。被购买
        
            
        });
        return [
            "code"=>666,
            "msg"=>"购买成功",
            "data"=>$data,
        ];
//        Db::startTrans();
//            Ret::IfEmptyExit( Db::table("article")->alias("a")->join("users u","u.id=a.user_id")->where([
//                "a.effect"=>1,
//                "a.id"=>$id
//            ])->field("a.*,u.name as author_name")->find(),10104);
//        Db::rollback();
//        try{
//            
//        }catch (\Exception  $Exception ){
//             Db::rollback();
//        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $post=$request->post();
        $validate=[
            "title|标题"=>"require|max:50|chsDash",
            "brief|文章简介"=>"require|max:100",
            "body|文章内容"=>"require",
            "expenses|文章资费"=>"require|float",
        ];
        Ret::IfNoTrue($this->validate($post, $validate), 10121);
        $data=Eliminate::E($post, $validate);
        $data['img']=$request->post("img");

        Ret::Exit_(\think\Db::table("article")->where(['id'=>$id])->update($data), 10122);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if(!isset($id))
            return Ret::err('10001','need article id');
        $article = Db::table("article")->where(["id"=>$id])->find();
        if($article['user_id'] !== Session::get("user.id"))
            return Ret::err('10001','permission deny');

        if (Db::table("article")->where(["id"=>$id])->update(['effect' => 0]))
            return Ret::ok();
        else
            return Ret::err('10001','database error');
    }
}
